package com.study.spring.mybatisCursor.controller;

import com.study.spring.mybatisCursor.FooMapper;
import com.study.spring.mybatisCursor.entity.User;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2021-11-14 21:11:43
 */
@RestController
@RequestMapping("user")
@ConditionalOnBean(DataSourceAutoConfiguration.class)
public class UserController {

    @Autowired
    FooMapper fooMapper;


   @Autowired
    private SqlSessionTemplate sqlSessionTemplate;


    @GetMapping("foo/scan/0/{limit}")
    @Transactional // 方案二，使用事务注解
    public void scanFoo0(@PathVariable("limit") int limit) throws Exception {
//        Cursor<Object> cursor = null;
//        SqlSession sqlSession = null;
//        try {
//            sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession();
//            cursor = sqlSession.selectCursor(FooMapper.class.getName() + ".scan");
//            cursor.forEach(e -> {
//                // 处理逻辑
//                System.out.println(e.toString());
//            });
//            // 也可以使用迭代器：Iterator<Object> iterator = cursor.iterator();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (null != cursor) {
//                try {
//                    cursor.close();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//            if (null != sqlSession) {
//                try {
//                    sqlSession.close();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }



        //方案一，可以用 SqlSessionFactory 来手工打开数据库连接
//        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession();
//        try (Cursor<User> cursor = sqlSession.getMapper(FooMapper.class).scan(limit) ) {  // 1
//            cursor.forEach(foo -> {
//                System.out.println(foo.getId());;
//            });                      // 2
//        }

        try (Cursor<User> cursor = fooMapper.scan(limit)) {
            cursor.forEach(foo -> {
                System.out.println(foo.getId());;
            });
        }

    }

}
